package com.hefan.robot.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.TopicRegistryDev;
import com.hefan.common.ons.TopicRegistryTest;
import com.hefan.common.ons.listener.GLLMessageListener;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.LivingRoomInfoVo;
import com.hefan.live.bean.RobotListenerVo;
import com.hefan.live.itf.LiveImOptService;
import com.hefan.live.itf.LivingRedisOptService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by nigle on 2016/12/7.
 */
@Component
public class RobotActionLightListener implements GLLMessageListener {

    Logger logger = LoggerFactory.getLogger(RobotActionLightListener.class);

    @Resource
    LiveImOptService liveImOptService;
    @Resource
    LivingRedisOptService livingRedisOptService;

    @Override
    public TopicRegistry getTopicRegistry() {
        return TopicRegistry.HEFAN_ROBOT_ACTION_LIGHT_DELAY ;
    }

    @Override
    public TopicRegistryDev getTopicRegistryDev() {
        return TopicRegistryDev.HEFAN_ROBOT_ACTION_LIGHT_DELAY_DEV;
    }

    @Override
    public TopicRegistryTest getTopicRegistryTest() {
        return TopicRegistryTest.HEFAN_ROBOT_ACTION_LIGHT_DELAY_TEST;
    }

    /**
     * 机器人首次点亮直播间
     * vo.getUser() 机器人对象 所需属性 userId、headImg、userType、userLevel、nickName
     * */
    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        String realTopic = message.getTag();
//        logger.info("机器人进直播间首次点亮-开始： receiver MessageListener topic: {}, realTopic : {}, msg_body: {}",
//                message.getTopic(), realTopic, new String(message.getBody()));
        logger.info("机器人进直播间首次点亮-开始");
        try {
            logger.info("message::{}",JSON.toJSONString(message));
            Map map = new ObjectMapper().readValue(message.getBody(), Map.class);
            if (null != map && !map.isEmpty()) {
                String voStr = (String) map.get("vo");
                logger.info("voStr::{}",voStr);
                RobotListenerVo vo = JSONObject.parseObject(voStr, RobotListenerVo.class);
                logger.info("vo::{}",JSON.toJSON(vo));
                if (null == vo) {
                    logger.info("RobotListenerVo解析失败");
                    return Action.CommitMessage;
                }

                if (!livingRedisOptService.isExistsLivingInfo_Hash(vo.getAnchId())) {
                    logger.info("直播{}已经结束，停止发送首次点亮IM消息",vo.getLiveUuid());
                    return Action.CommitMessage;
                }

                String str = livingRedisOptService.getLivingInfo_Hash(vo.getAnchId());
                if (StringUtils.isBlank(str)) {
                    logger.error("直播信息获取失败");
                    return Action.CommitMessage;
                }
                LivingRoomInfoVo livingVo = JSON.parseObject(str, LivingRoomInfoVo.class);
                if (null == livingVo) {
                    logger.error("直播信息解析失败");
                    return Action.CommitMessage;
                }
                if (!livingVo.getLiveUuid().equals(vo.getLiveUuid())) {
                    logger.info("直播{}已经结束，停止发送首次点亮IM消息",vo.getLiveUuid());
                    return Action.CommitMessage;
                }

                if (!livingRedisOptService.IMSendCheck(vo.getAnchId(),2)){
                    logger.info("太多了不能再发送首次点亮的IM消息了，{}",vo.getLiveUuid());
                    return Action.CommitMessage;
                }
                //判断是否还在直播间
                Long result = livingRedisOptService.isInRoom(vo.getAnchId(), vo.getLiveRoomPersonVo().getUserId());
                if (null == result) {
                    logger.info("{}已经不在{}的直播间了，停止动作",vo.getLiveRoomPersonVo().getUserId(),vo.getAnchId());
                    return Action.CommitMessage;
                }
                logger.info("各种判断做完了");
                ResultBean rb = liveImOptService.lightRoom(vo.getChatRoomId(), vo.getLiveUuid(), vo.getLiveRoomPersonVo());
                if (null != rb && rb.getCode() == ResultCode.SUCCESS.get_code()) {
                    logger.info("机器人：{}首次点亮直播：{}发送IM成功；code：{}，msg：{}" , vo.getLiveRoomPersonVo().getUserId() , vo.getLiveUuid() ,String.valueOf(rb.getCode()),rb.getMsg());
                }else {
                    rb = liveImOptService.lightRoom(vo.getChatRoomId(), vo.getLiveUuid(), vo.getLiveRoomPersonVo());
                    if (null != rb && rb.getCode() == ResultCode.SUCCESS.get_code()) {
                        logger.info("机器人：{}首次点亮直播：{}发送IM成功；code：{}，msg：{}" , vo.getLiveRoomPersonVo().getUserId() , vo.getLiveUuid() ,String.valueOf(rb.getCode()),rb.getMsg());
                    }else {
                        rb = liveImOptService.lightRoom(vo.getChatRoomId(), vo.getLiveUuid(), vo.getLiveRoomPersonVo());
                        if (null != rb && rb.getCode() == ResultCode.SUCCESS.get_code()) {
                            logger.info("机器人：{}首次点亮直播：{}发送IM成功；code：{}，msg：{}" , vo.getLiveRoomPersonVo().getUserId() , vo.getLiveUuid() ,String.valueOf(rb.getCode()),rb.getMsg());
                        }else {
                            logger.info("机器人：{}首次点亮直播：{}尝试发送三次IM失败；code：{}，msg：{}" , vo.getLiveRoomPersonVo().getUserId() , vo.getLiveUuid() ,String.valueOf(rb.getCode()),rb.getMsg());
                        }
                    }
                }
                return Action.CommitMessage;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("HEFAN_ROBOT_ACTION_LIGHT_DELAY receiver MessageListener ERROR：" + e.getMessage());
            return Action.CommitMessage;
        } finally {
            logger.info("HEFAN_ROBOT_ACTION_LIGHT_DELAY receiver MessageListener END");
            return Action.CommitMessage;
        }
    }
}
